<template>
  <div class="map-container">
    <div class="map-title">{{ currentTitle }}</div>
    <div class="map-controls">
      <button v-if="drillLevel > 0" @click="drillUp" class="drill-btn">
        <i class="el-icon-back"></i> 返回上级
      </button>
    </div>
    <div ref="mapChart" class="map-chart"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import 'echarts/map/js/world'
import 'echarts/map/js/china'
// 引入省份地图数据
import guangdong from 'echarts/map/json/province/guangdong.json'
import beijing from 'echarts/map/json/province/beijing.json'
// 可以添加更多省份

export default {
  name: 'DrillDownMap',
  data() {
    return {
      chart: null,
      drillLevel: 0, // 0-世界，1-国家，2-省，3-市
      currentGeoJson: null,
      currentTitle: '世界地图1',
      historyStack: [], // 用于存储上钻历史
      mapData: {
        world: {
          name: '世界',
          data: [
            {name: 'China', value: 100},
            {name: 'United States', value: 85},
            {name: 'Japan', value: 70}
          ]
        },
        china: {
          name: '中国',
          data: [
            {name: '广东', value: 90},
            {name: '北京', value: 80},
            {name: '上海', value: 85}
          ]
        },
        Russia: {
          name: '俄罗斯',
          data: [
            {name: 'ural', value: 95},
            {name: 'krasnodar', value: 90},
            {name: 'moscow', value: 88}
          ]
        },
        provinces: {
          guangdong: {
            name: '广东省',
            data: [
              {name: '广州', value: 95},
              {name: '深圳', value: 90},
              {name: '珠海', value: 80}
            ]
          },
          beijing: {
            name: '北京市',
            data: [
              {name: '朝阳区', value: 85},
              {name: '海淀区', value: 90},
              {name: '西城区', value: 88}
            ]
          }
        }
      }
    }
  },
  mounted() {
    this.initChart()
    this.loadWorldMap()
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose()
    }
    window.removeEventListener('resize', this.resizeHandler)
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$refs.mapChart)
      window.addEventListener('resize', this.resizeHandler)
    },

    resizeHandler() {
      this.chart && this.chart.resize()
    },

    // 加载世界地图
    loadWorldMap() {
      // echarts.registerMap('world', require('echarts/map/json/world.json'))
      echarts.registerMap('world', require('@/assets/Alabama, admin2 .geo.json'))
      // echarts.registerMap('world', require('@/assets/中华人民共和国.json'))
      // echarts.registerMap('world', require('@/assets/allmap/countries.geo.json'))
      // https://geo.datav.aliyun.com/areas_v2/bound/100000_full.json


      const option = this.getBaseOption('世界地图')
      option.series[0].map = 'world'
      option.series[0].data = this.mapData.world.data

      this.currentGeoJson = 'world'
      this.drillLevel = 0
      this.currentTitle = '世界地图'
      this.historyStack = [] // 重置历史栈

      this.chart.setOption(option, true)
      this.bindMapClick()
    },

    // 加载国家地图
    loadCountryMap(countryName) {
    console.log("countryName",countryName);

      if (countryName === 'China' || countryName === '中国') {
        echarts.registerMap('china', require('echarts/map/json/china.json'))
        // echarts.registerMap('china', require('@/assets/中华人民共和国.json'))
        // echarts.registerMap('china', require('@/assets/广州市.json'))
        // echarts.registerMap('china', require('@/assets/allmap/countries/CHN.geo.json'))

        const option = this.getBaseOption('中国地图')
        option.series[0].map = 'china'
        option.series[0].data = this.mapData.china.data

        // 保存当前状态到历史栈
        this.historyStack.push({
          geoJson: this.currentGeoJson,
          title: this.currentTitle,
          level: this.drillLevel
        })

        this.currentGeoJson = 'china'
        this.drillLevel = 1
        this.currentTitle = '中国地图'

        this.chart.setOption(option, true)
        this.bindMapClick()
        // eslint-disable-next-line no-empty
      } else if (countryName === "India") {
        // echarts.registerMap('china', require('echarts/map/json/china.json'))
        echarts.registerMap('Russia', require('@/assets/maps'))

        const option = this.getBaseOption('俄罗斯')
        option.series[0].map = 'Russia'
        option.series[0].data = this.mapData.Russia.data

        // 保存当前状态到历史栈
        this.historyStack.push({
          geoJson: this.currentGeoJson,
          title: this.currentTitle,
          level: this.drillLevel
        })

        this.currentGeoJson = 'Russia'
        this.drillLevel = 1
        this.currentTitle = '俄罗斯'

        this.chart.setOption(option, true)
        this.bindMapClick()
      } else {
        this.$message.warning('暂不支持该国家下钻')
      }
    },

    // 加载省份地图
    loadProvinceMap(provinceName) {
      console.log("provinceName",provinceName);

      const provinceKey = this.getProvinceKey(provinceName)
      if (!provinceKey || !this.mapData.provinces[provinceKey]) {
        this.$message.warning('暂不支持该省份下钻')
        return
      }

      try {
        // 注册省份地图
        const provinceJson = this.getProvinceJson(provinceKey)
        if (!provinceJson) {
          this.$message.warning('该省份地图数据未加载')
          return
        }
        echarts.registerMap(provinceKey, provinceJson)

        const option = this.getBaseOption(provinceName + '地图')
        option.series[0].map = provinceKey
        option.series[0].data = this.mapData.provinces[provinceKey].data

        // 保存当前状态到历史栈
        this.historyStack.push({
          geoJson: this.currentGeoJson,
          title: this.currentTitle,
          level: this.drillLevel
        })

        this.currentGeoJson = provinceKey
        this.drillLevel = 2
        this.currentTitle = provinceName + '地图'

        this.chart.setOption(option, true)
        this.bindMapClick()
      } catch (e) {
        console.error('加载省份地图失败:', e)
        this.$message.error('加载省份地图失败')
      }
    },

    // 上钻功能
    drillUp() {
      if (this.historyStack.length === 0) return

      const prev = this.historyStack.pop()

      switch (prev.level) {
        case 0:
          this.loadWorldMap()
          break
        case 1:
          this.loadCountryMap(prev.title)
          break
        case 2:
          this.loadProvinceMap(prev.title)
          break
      }
    },

    // 地图点击事件处理
    handleMapClick(params) {
      console.log("params",params)
      if (!params.name) return

      switch (this.drillLevel) {
        case 0: // 世界地图点击
          this.loadCountryMap(params.name)
          break
        case 1: // 国家地图点击
          this.loadProvinceMap(params.name)
          break
        case 2: // 省份地图点击
          // 这里可以继续下钻到城市
          this.$message.info(`点击了 ${params.name}，可在此实现下钻到城市`)
          break
      }
    },

    // 绑定地图点击事件
    bindMapClick() {
      this.chart.off('click')
      this.chart.on('click', this.handleMapClick)
    },

    // 获取基础配置
    getBaseOption(title) {
      return {
        title: {
          text: title,
          left: 'center',
          textStyle: {
            fontSize: 18
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: params => {
            return `${params.name}<br/>数值: ${params.value || '无数据'}`
          }
        },
        visualMap: {
          min: 0,
          max: 100,
          text: ['高', '低'],
          realtime: false,
          calculable: true,
          inRange: {
            color: ['#50a3ba', '#eac736', '#d94e5d']
          },
          bottom: 30
        },
        series: [{
          name: '地图数据',
          type: 'map',
          roam: true,
          scaleLimit: {
            min: 1,
            max: 3
          },
          label: {
            show: true,
            fontSize: 10
          },
          emphasis: {
            label: {
              show: true
            },
            itemStyle: {
              areaColor: '#ffcc00'
            }
          },
          itemStyle: {
            areaColor: '#e0ffff',
            borderColor: '#000'
          },
          data: []
        }]
      }
    },

    // 省份名称转key
    getProvinceKey(provinceName) {
      const map = {
        '广东': 'guangdong',
        '北京': 'beijing',
        '上海': 'shanghai',
        '江苏': 'jiangsu',
        '浙江': 'zhejiang'
        // 可以添加更多省份
      }
      return map[provinceName]
    },

    // 获取省份JSON数据
    getProvinceJson(provinceKey) {
      const map = {
        'guangdong': guangdong,
        'beijing': beijing
        // 可以添加更多省份
      }
      return map[provinceKey]
    }
  }
}
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 100%;
  position: relative;
  background: #f5f7fa;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.map-title {
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 10;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.map-controls {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
}

.drill-btn {
  padding: 8px 15px;
  background: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.drill-btn:hover {
  background: #66b1ff;
}

.drill-btn i {
  margin-right: 5px;
}

.map-chart {
  width: 100%;
  height: 800px;
  min-height: 500px;
}
</style>